﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NRSoft.IdentityServer.ClientA.Models;

namespace NRSoft.IdentityServer.ClientA.Controllers
{
    public class HomeController : AbpController
    {
        [Authorize]
        public async Task GetUserInfo()
        {
            var json = "";
            if (User != null)
            {
                foreach (var claim in User.Claims)
                {
                    json += $"{claim.Type} = {claim.Value},";
                }
            }

            Response.ContentType = "text/html; charset=UTF-8";
            await Response.WriteAsync($"<script type=\"text/javascript\">alert('{json}');</script>", Encoding.UTF8);
        }

        [Authorize]
        public IActionResult Secure()
        {
            var userId = User.Identity.Name;

            return this.Content($"当前登录用户的ID为：{userId}");
        }

        public IActionResult Logout()
        {
            // 建议采用下面这种方式
            //await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            //await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);

            // 先清空本地Cookie，然后调用OpenId到远程登出（SSO站点），最后通过Iframe的方式清空所有客户端
            // 客户端要求设置了FrontChannelLogoutUri，并且是登录过的，才会通过Iframe的方式清空Cookie。
            // 没有登录过的客户端就没必要清空了，因为根本就没有cookie，也就不浪费资源去清空了。
            return SignOut(CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
